let express = require('express')
let router = express.Router()

let mysqlHelper = require('../utils/mysqlHelper.js')
const utils = require('../utils/utils.js')

// 查询所有用户
router.get('/all', async function (req, res, next) {
    let result = {}
    try {
        let sqlStr = "select * from base_device a "
        result.code = 200
        result.data = await mysqlHelper.query(sqlStr)
    } catch (err) {
        result.code = 400
        result.err = err.message
    }
    res.json(result)
})

// 查询 maoyuan  keyword分页检索
router.get('/list', async function (req, res, next) {
    let result = {}
    try {
        let page = utils.getQueryValue(req.query.page)
        let pageSize = utils.getQueryValue(req.query.pageSize)
        let sqlLimit = " limit " + (page - 1) * pageSize + ", " + pageSize
        sqlLimit = ((sqlLimit.indexOf('NaN')>-1 || sqlLimit.indexOf("undefined")>-1|| page=='' || pageSize=='') ? "" : sqlLimit)
        let keyword = utils.getQueryValue(req.query.keyword)
        let groupId = utils.getQueryValue(req.query.groupId)
        let deviceType = utils.getQueryValue(req.query.deviceType)
        let sqlWhere = " where 1=1"
        sqlWhere += (keyword != '' ? " and (u.DeviceName like '%" + keyword + "%' or u.DeviceNumber like '%" + keyword + "%') " : "")
        sqlWhere += (groupId != '' ? " and u.orgId=" + groupId : "")
        sqlWhere += (deviceType!=''? " and u.deviceType='"+deviceType+"'":"")
        total = (await mysqlHelper.query("select count(1) as ct from base_device u " + sqlWhere))[0].ct

        let prop = utils.getQueryValue(req.query.prop)
        let order = utils.getQueryValue(req.query.order)
        if (order=='ascending')
            order="ASC"
        else if (order=='descending')
            order='DESC'
        let sqlOrder = " ORDER by " + prop+" "+ order
        sqlOrder = ((prop.indexOf('NaN')>-1 || order.indexOf("undefined")>-1 || prop=='' || order=='') ? "" : sqlOrder)

        let sqlStr = "SELECT u.*,o.orgName,getParentList(o.orgId) as fullorgName from base_device u left join sys_organization o  on u.orgId=o.orgId "
        sqlStr += sqlWhere + sqlOrder + sqlLimit
        rows = await mysqlHelper.query(sqlStr)
        rows.forEach((user, index, arr) => {
            user.group = (user.group ? user.group.split(',') : [])
            user.parentId = (user.parentId ? [user.parentId] : [])
            user.brotherDeviceId = (user.brotherDeviceId ? user.brotherDeviceId.split(',') : [])
            user.childDeviceId = (user.childDeviceId ? user.childDeviceId.split(',') : [])
        })
        result.code = 200
        result.data = {
            'total': total,
            'page': page,
            'pageSize': pageSize,
            'summary': {
                'id': page * pageSize,
                'name': '999'
            },
            rows: rows
        }
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

// 新增修改 maoyuan
router.post('/', async function (req, res, next) {
    let result = {}
    try {
        let deviceType = utils.getQueryValue(req.body.deviceType)===''?null:"'"+req.body.deviceType+"'"
        let deviceName = utils.getQueryValue(req.body.deviceName)===''?null:"'"+req.body.deviceName+"'"   
        let remark = utils.getQueryValue(req.body.remark)===''?null:"'"+req.body.remark+"'"      
        let parentId = utils.getQueryValue(req.body.parentId)==''?null:req.body.parentId
        let deviceNumber = utils.getQueryValue(req.body.deviceNumber)==''?null:"'"+req.body.deviceNumber+"'"
        let priority = utils.getQueryValue(req.body.priority)==''?0:req.body.priority
        let frequency1 = utils.getQueryValue(req.body.frequency1)==''?'':req.body.frequency1
        let frequency2 = utils.getQueryValue(req.body.frequency2)==''?'':req.body.frequency2
        let capacity1 = utils.getQueryValue(req.body.capacity1)==''?'':req.body.capacity1
        let capacity2 = utils.getQueryValue(req.body.capacity2)==''?'':req.body.capacity2
        let brotherDeviceId = utils.getQueryValue(req.body.brotherDeviceId)==''?null:"'"+req.body.brotherDeviceId+"'"        
        let childDeviceId = utils.getQueryValue(req.body.childDeviceId)==''?null:"'"+req.body.childDeviceId+"'"
        let status = utils.getQueryValue(req.body.deviceNumber)==''?0:req.body.status
        let orgId = Array.isArray(req.body.orgId) ? req.body.orgId[req.body.orgId.length - 1] : req.body.orgId

        let sqlStr = ""
        let id = utils.getQueryValue(req.body.deviceId)
        if (id == '') { //新增
            if ((await mysqlHelper.query("select count(1) as ct from base_device where deviceName='" + req.body.deviceName + "'"))[0].ct > 0) {
                throw new Error('该设备名称已被使用。')
            } else {
                sqlStr = "insert into base_device(deviceType,deviceName,parentId,deviceNumber,priority,orgId,frequency1,frequency2,capacity1,capacity2,brotherDeviceId,childDeviceId,status,remark) values (" 
                    +deviceType+","+deviceName+","+parentId+","+deviceNumber+","+priority+","+orgId+","+frequency1+","+frequency2+","+capacity1+","+capacity2
                    +","+brotherDeviceId+ ","+childDeviceId+ ","+status+ ","+remark+")"
                result.data = await mysqlHelper.query(sqlStr)
            }
        } else { //修改            
            sqlStr = "UPDATE base_device SET deviceType="+deviceType+",deviceName="+deviceName+",parentId="+parentId+",deviceNumber="+deviceNumber+",priority="+priority+",orgId="+orgId
                    +",frequency1="+frequency1+",frequency2="+frequency2+",capacity1="+capacity1+",capacity2="+capacity2+",brotherDeviceId="+brotherDeviceId+",childDeviceId="+childDeviceId 
                    +",remark="+remark+",status="+req.body.status+" WHERE deviceId=" + id
            result.data = await mysqlHelper.query(sqlStr)
        }
        result.code = 200
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

// 删除  maoyuan
router.delete('/', async function (req, res, next) {
    let result = {}
    try {
        result.code = 200
        result.data = await mysqlHelper.query("delete from base_device where deviceId in (" + req.body.ids.join() + ")")
        result.success = true
    } catch (err) {
        result.code = 400
        result.success = false
        result.message = err.message
    }
    res.json(result)
})

module.exports = router
